package sql

import (
	"fmt"
	"game/game-db/orm/meta"
)

type ISql interface {
	InsertHeadSql() string
	InsertBodySql() string
	InsertSql() string
	UpdateSql() string
	DeleteSql() string
}

// 构建通过主键查询的语句
func buildSelectSql(entityMeta meta.IEntityMeta, tableName string) string {
	return fmt.Sprintf("SELECT * FROM `%s` WHERE `%s`=?", tableName, entityMeta.PrimaryKeyName())
}

// 构建查询所有的语句
func buildSelectAllSql(tableName string) string {
	return fmt.Sprintf("SELECT * FROM `%s`", tableName)
}

// 构建插入语句的头部分
func buildInsertHeadSql(entityMeta meta.IEntityMeta, tableName string) string {
	sql := fmt.Sprintf("INSERT INTO `%s` (", tableName)
	for i, column := range entityMeta.Columns() {
		if i != 0 {
			sql += ","
		}
		sql += fmt.Sprintf("`%s`", column.ColumnName())
	}
	sql += ") VALUES"
	return sql
}

// 构建插入语句的体部分
func buildInsertBodySql(entityMeta meta.IEntityMeta) string {
	sql := "("
	for i := range entityMeta.Columns() {
		if i != 0 {
			sql += ","
		}
		sql += "?"
	}
	sql += ")"
	return sql
}

// 构建更新语句
func buildUpdateSql(entityMeta meta.IEntityMeta, tableName string) string {
	sql := fmt.Sprintf("UPDATE `%s` SET ", tableName)
	isFirst := true
	for _, column := range entityMeta.Columns() {
		if column.ReadOnly() {
			continue
		}
		if column.ColumnName() == entityMeta.PrimaryKeyName() {
			continue
		}
		if !isFirst {
			sql += ","
		}
		sql += fmt.Sprintf("`%s`=?", column.ColumnName())
		isFirst = false
	}
	sql += fmt.Sprintf(" WHERE `%s`=?", entityMeta.PrimaryKeyName())
	return sql
}

// 构建删除语句
func buildDeleteSql(entityMeta meta.IEntityMeta, tableName string) string {
	return fmt.Sprintf("DELETE FROM `%s` WHERE `%s`=?", tableName, entityMeta.PrimaryKeyName())
}
